package com.meiyue.locallibs.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * MeiyueJavaProject
 * com.meiyue.locallibs.websocket
 * Created by Chris Chen
 * 2017/9/16
 * Explain:
 */
@ServerEndpoint("/socket")
@Component
public class MyWebSocket {

    private CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        sendMessage("有人来了");
    }

    @OnClose
    public void onClose(Session session) {

    }

    @OnMessage
    public void onMessage(String message, Session session) {
        sendMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {

    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
